package com.tanhua.dubbo.api;

import cn.hutool.core.util.PageUtil;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class VideoApiImpl implements VideoApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override//发布短视频，将短视频对象保存在数据库中
    public void saveVideo(Video video) {
        mongoTemplate.save(video);
    }

    @Override//查询全部视频
    public List<Video> findAll(Integer page, Integer pagesize) {
        //1.构建分页查询条件
        Query query = new Query().with(Sort.by(Sort.Order.desc("created")))
                .limit(pagesize)
                .skip((page - 1) * pagesize);

        return mongoTemplate.find(query,Video.class);
    }

    @Override//根据id查询，如果redis足够分页就展示推荐的数据，如果不足以分页就查询所有
    public List<Video> findList(String[] ids, Integer page, Integer pagesize) {
        int totalPage= PageUtil.totalPage(ids.length, pagesize);
        //如果前端传递的page，小于totalPage，说明redis中的数据足够分页
        if (page<=totalPage){
            Criteria criteria = Criteria.where("id").in(ids);
            Query query = Query.query(criteria)
                    .limit(pagesize)
                    .skip(page);
            return mongoTemplate.find(query,Video.class);
        }else{
           return  findAll(page-totalPage,pagesize);
        }
    }

    @Override//后台需求：根据id查询用户视频分页列表
    public PageResult findByPage(Integer page, Integer pagesize, Long userId) {
        //1.构建Criteria
        Criteria criteria = Criteria.where("userId").is(userId);
        //2.构建Query
        Query query = Query.query(criteria);
        //3.查询总数
        long count = mongoTemplate.count(query, Video.class);
        //4.再次构建Query
        query=query.with(Sort.by(Sort.Order.desc("created")))
                .skip((page-1)*pagesize)
                .limit(pagesize);
        //5.查询需要的数据
        List<Video> list = mongoTemplate.find(query, Video.class);
        return new PageResult(page,pagesize,count,list);
    }
}
